package com.zmn.oms.zmn.facade.impl.order;

import com.alibaba.fastjson.JSON;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.oms.business.interfaces.order.DuplicateOrderBService;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.model.dto.order.OrderOperationInstructionMessage;
import com.zmn.oms.model.dto.work.modify.must.ZsCancelDTO;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.base.oms.common.model.es.orderwork.EsOrderWork;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.zmn.facade.interfaces.order.CancelOrderFacade;
import com.zmn.oms.zmn.normal.business.interfaces.work.ZsNormalWorkBService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.Optional;

/**
 * 类描述：
 *
 * @author lhl
 * @date 2020/03/02 21:53
 */
@Slf4j
@Service("cancelOrderFacade")
public class CancelOrderFacadeImpl implements CancelOrderFacade {

    @Autowired
    private ZsNormalWorkBService zsNormalWorkBService;
    @Autowired
    protected OrderWorkService orderWorkService;
    @Autowired
    private DuplicateOrderBService duplicateOrderBService;

    @Override
    public ResultDTO cancelOrderByOperationInstructionMessage(OrderOperationInstructionMessage message) {
        try {
            Long orderId = message.getOrderId();
            OrderWork dbOrderWork = orderWorkService.findOrderWorkByKey(orderId, orderId);

            if (dbOrderWork == null) {
                log.info("【操作指令】订单不存在: orderId=[{}]", orderId);
                return ResultDTO.fail("订单不存在");
            }

            ZsCancelDTO cancelDTO = new ZsCancelDTO();
            cancelDTO.setOrderId(orderId);
            cancelDTO.setWorkId(orderId);
            cancelDTO.setContent(message.getRemark());
            cancelDTO.setExtra(message.getExtra());

            // 超时未支付取消
            boolean isPayTimeout = Objects.equals(GlobalConsts.YES, message.getPayTimeout());
            cancelDTO.setPayTimeout(isPayTimeout ? GlobalConsts.YES : GlobalConsts.NO);
            // 操作人ID、类型
            cancelDTO.setOperatorId(Optional.ofNullable(message.getOperatorId()).orElse(0L));
            cancelDTO.setOperatorType(Optional.ofNullable(message.getOperatorType()).orElse(GlobalConsts.OPERATE_USER_TYPE_SYSTEM));

            log.info("【操作指令】取消订单: ZsCancelDTO:[{}]", JSON.toJSONString(cancelDTO));
            zsNormalWorkBService.saveCancel(cancelDTO);

            return ResultDTO.success();

        } catch (Exception e) {
            log.error("【操作指令】取消订单失败: {}", e.getMessage(), e);

            if (e instanceof OmsBaseException) {
                return ResultDTO.fail("取消失败："+ e.getMessage());
            }
            return ResultDTO.fail("取消失败");
        }
    }
}
